<?php


namespace app\common\controller;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use app\BaseController;
use app\common\util\Result;
use app\common\exception\CatchException;

class JwtBaseController extends BaseController
{

    protected $failException = true;

    /**
     * $key jwt HS256 key
     *
     * @var string
     */
    protected $key;

    protected function getKey()
    {
        return $this->key;
    }

    /**
     * 设置jwt密钥
     *
     * @param mixed $key
     *
     * @return void
     */
    protected function setKey($key)
    {
        $this->key = $key;
    }

    /**
     * 验证token
     *
     * @return mixed
     */
    public function valid()
    {
        // 允许 Authorization 头部通过 cors
        $jwt = $this->request->header('Authorization');
        if (!$jwt) {
            $jwt = $this->request->param("token");
        }
        if (empty($jwt)) {
            throw new CatchException("未授权用户", 600);
        }

        $jwt = str_replace('Bearer ', '', $jwt);
        // try decode
        $this->decodeJwt($jwt);
        return Result::rest(true);
    }

    /**
     * 默认参数
     *
     * @return mixed
     */
    protected function params($validator = null, $name = '')
    {
        $params = $this->request->param($name, null, 'trim');
        // 尝试校验
        if (!is_null($validator)) {
            $this->validate($params, $validator);
        }
        return $params;
    }

    protected function only(array $names)
    {
        return $this->request->only($names);
    }

    /**
     * encodeJwt
     *
     * @param array $payload
     *
     * @return string
     */
    protected function encodeJwt(array $payload)
    {
        return JWT::encode($payload, $this->getKey(), 'HS256');
    }

    /**
     * decodeJwt
     *
     * @param string $jwt
     *
     * @return \stdClass
     */
    protected function decodeJwt($jwt)
    {
        return JWT::decode($jwt, new Key($this->getKey(), 'HS256'));
    }

}